package com.yifeng.servlet.admin;

import com.yifeng.common.Result;
import com.yifeng.factory.ServiceFactory;
import com.yifeng.service.ResourceService;
import com.yifeng.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 创建一个新的 ResourcePublicServlet 类处理公开查询
@WebServlet("/resources/*")
public class ResourcesPublicServlet extends BaseServlet {
    private final ResourceService resourceService = ServiceFactory.getResourceService();

    @Override
    protected void doHandle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if ("GET".equals(req.getMethod().toUpperCase())) {
            handleGet(req, resp, req.getPathInfo());
        } else {
            writeJson(resp, Result.fail(405,"请求方法错误"));
        }
    }

    private void handleGet(HttpServletRequest req, HttpServletResponse resp, String pathInfo) throws IOException {
        // 处理 pathInfo 为 null 的情况
        if (pathInfo == null) {
            pathInfo = "/"; // 统一视作根路径
        }
        // 现在 pathInfo 肯定不为 null，可以安全使用
        if (!pathInfo.equals("/") && !pathInfo.isEmpty()) {
            // 检查是否是下载路径：/123/download
            if (pathInfo.matches("^/\\d+/download$")) {
                String resourceIdStr = pathInfo.substring(1, pathInfo.lastIndexOf("/"));
                handleDownload(req, resp, resourceIdStr);
                return;
            }
            // 其他非根路径（如 /123）暂不支持
            writeJson(resp, Result.fail(406,"暂不支持单条资源查询"));
            return;
        }


        // 获取搜索关键词
        String keyword = req.getParameter("keyword");


        if (keyword != null && !keyword.trim().isEmpty()) {
            Result result = resourceService.searchResources(keyword.trim());
            writeJson(resp, result);
        } else {
            Result result = resourceService.getAllResources();
            writeJson(resp, result);

        }
    }

    //处理下载
    private void handleDownload(HttpServletRequest req, HttpServletResponse resp, String resourceIdStr) throws IOException {



        try {
            int resourceId = Integer.parseInt(resourceIdStr);
            Result result = resourceService.downloadResource(resourceId, resp);
            if (result != null) {
                // 仅当 result 不为 null 时才写 JSON（说明出错）
                writeJson(resp, result);
            }
            // 如果 result == null，说明已成功写入文件流，无需再响应
        } catch (NumberFormatException e) {
            writeJson(resp, Result.fail(400,"新闻ID格式错误"));
        }
    }
}